# 方法1：直接读取（自动关闭文件）
with open('example.txt', 'r', encoding='utf-8') as f:
    content = f.read()  # 读取全部内容
    print(content)

# 方法2：逐行读取
with open('example.txt', 'r', encoding='utf-8') as f:
    for line in f:  # 逐行迭代
        print(line.strip())  # strip()去除首尾空白符




# 覆盖写入（文件已存在则清空）
with open('output.txt', 'w', encoding='utf-8') as f:
    f.write("第一行内容\n")
    f.write("第二行内容\n")  # 需手动添加换行符

# 写入多行（writelines接收可迭代对象）
lines = ["第三行\n", "第四行\n"]
with open('output.txt', 'w', encoding='utf-8') as f:
    f.writelines(lines)

with open('output.txt', 'a', encoding='utf-8') as f:
        f.write("这是追加的内容\n")






import csv

# 写入CSV文件
data = [
    ['姓名', '年龄', '城市'],
    ['张三', 25, '北京'],
    ['李四', 30, '上海']
]

with open('people.csv', 'w', encoding='utf-8', newline='') as f:
    writer = csv.writer(f)
    writer.writerows(data)  # 写入多行

# 读取CSV文件
with open('people.csv', 'r', encoding='utf-8') as f:
    reader = csv.reader(f)
    for row in reader:
        print(row)  # 每行作为列表返回




# 写入字典形式CSV
import csv

data_dict = [
    {'name': '张三', 'age': 25, 'city': '北京'},
    {'name': '李四', 'age': 30, 'city': '上海'}
]

with open('people_dict.csv', 'w', encoding='utf-8', newline='') as f:
    fieldnames = ['name', 'age', 'city']
    writer = csv.DictWriter(f, fieldnames=fieldnames)
    writer.writeheader()  # 写入表头
    writer.writerows(data_dict)

# 读取字典形式CSV
with open('people_dict.csv', 'r', encoding='utf-8') as f:
    reader = csv.DictReader(f)
    for row in reader:  # 每行作为OrderedDict返回
        print(f"{row['name']} 居住在 {row['city']}")



import csv

def save_grades(filename, students):
    """将学生成绩保存为CSV"""
    with open(filename, 'w', encoding='utf-8', newline='') as f:
        writer = csv.DictWriter(f, fieldnames=['学号', '姓名', '成绩'])
        writer.writeheader()
        writer.writerows(students)

def load_grades(filename):
    """从CSV加载学生成绩"""
    with open(filename, 'r', encoding='utf-8') as f:
        return list(csv.DictReader(f))

# 使用示例
students = [
    {'学号': '1001', '姓名': '张三', '成绩': '85'},
    {'学号': '1002', '姓名': '李四', '成绩': '92'}
]

save_grades('grades.csv', students)
loaded_data = load_grades('grades.csv')
print(loaded_data)








import os
import shutil
from datetime import datetime


def backup_file(src_path):
    """备份文本文件（保留原始格式）"""
    # 生成备份文件名（原文件名+时间戳）
    timestamp = datetime.now().strftime("%Y%m%d_%H%M%S")
    base_name = os.path.basename(src_path)
    backup_name = f"{os.path.splitext(base_name)[0]}_backup_{timestamp}.txt"
    backup_path = os.path.join("backups", backup_name)

    # 创建备份目录（如果不存在）
    os.makedirs("backups", exist_ok=True)

    # 执行备份
    try:
        shutil.copy2(src_path, backup_path)  # copy2会保留元数据
        print(f"成功备份到: {backup_path}")
        return True
    except Exception as e:
        print(f"备份失败: {e}")
        return False


# 使用示例
backup_file("data.txt")


def incremental_backup(src_path):
    """增量备份（比较修改时间）"""
    if not os.path.exists(src_path):
        print("源文件不存在")
        return

    backup_dir = "backups"
    os.makedirs(backup_dir, exist_ok=True)

    src_mtime = os.path.getmtime(src_path)
    latest_backup = None

    # 查找最新的备份文件
    for fname in os.listdir(backup_dir):
        if fname.startswith(os.path.basename(src_path)):
            backup_mtime = os.path.getmtime(os.path.join(backup_dir, fname))
            if not latest_backup or backup_mtime > latest_backup[1]:
                latest_backup = (fname, backup_mtime)

    # 比较修改时间
    if not latest_backup or src_mtime > latest_backup[1]:
        return backup_file(src_path)  # 使用之前的备份函数
    else:
        print("文件未修改，跳过备份")
        return False


def register_user(username, password, email):
    """注册用户（存储到文本文件）"""
    user_data = f"{username},{password},{email}\n"

    try:
        with open("users.txt", "a", encoding="utf-8") as f:
            f.write(user_data)
        print("注册成功！")
        return True
    except IOError as e:
        print(f"注册失败: {e}")
        return False


# 使用示例
register_user("alice", "p@ssw0rd", "alice@example.com")

import json


def json_register(username, password, email):
    """注册用户（JSON格式存储）"""
    new_user = {
        "username": username,
        "password": password,  # 实际应用中应该加密
        "email": email,
        "register_time": datetime.now().strftime("%Y-%m-%d %H:%M:%S")
    }

    users = []
    # 读取现有数据
    try:
        with open("users.json", "r", encoding="utf-8") as f:
            users = json.load(f)
    except (FileNotFoundError, json.JSONDecodeError):
        pass  # 文件不存在或为空时新建

    # 检查用户名是否已存在
    if any(u["username"] == username for u in users):
        print("用户名已存在")
        return False

    # 添加新用户并写入
    users.append(new_user)
    try:
        with open("users.json", "w", encoding="utf-8") as f:
            json.dump(users, f, indent=2, ensure_ascii=False)
        print("注册成功！")
        return True
    except IOError as e:
        print(f"注册失败: {e}")
        return False


# 使用示例
json_register("bob", "bob123", "bob@example.com")

import hashlib
import getpass  # 安全获取密码输入


def hash_password(password):
    """使用SHA-256哈希密码"""
    return hashlib.sha256(password.encode()).hexdigest()


def secure_register():
    """安全注册流程"""
    username = input("请输入用户名: ").strip()
    password = getpass.getpass("请输入密码: ")
    email = input("请输入邮箱: ").strip()

    user_data = {
        "username": username,
        "password_hash": hash_password(password),
        "email": email,
        "register_time": datetime.now().isoformat()
    }

    # 存储逻辑与之前JSON示例相同...
    # 需要添加用户名查重等逻辑


import json
import hashlib
from pathlib import Path


class UserSystem:
    def __init__(self, db_file="users.json"):
        self.db_file = Path(db_file)
        self.backup_dir = Path("backups")
        self.users = self._load_users()

    def _load_users(self):
        """加载用户数据"""
        if not self.db_file.exists():
            return []

        try:
            with open(self.db_file, "r", encoding="utf-8") as f:
                return json.load(f)
        except (json.JSONDecodeError, IOError) as e:
            print(f"加载用户数据失败: {e}")
            return []

    def _backup_db(self):
        """备份用户数据库"""
        self.backup_dir.mkdir(exist_ok=True)
        timestamp = datetime.now().strftime("%Y%m%d_%H%M%S")
        backup_file = self.backup_dir / f"users_backup_{timestamp}.json"

        try:
            shutil.copy2(self.db_file, backup_file)
            print(f"数据库已备份到: {backup_file}")
        except Exception as e:
            print(f"备份失败: {e}")

    def register(self, username, password, email):
        """注册新用户"""
        # 检查用户名是否已存在
        if any(u["username"] == username for u in self.users):
            print("用户名已存在")
            return False

        # 添加新用户
        self.users.append({
            "username": username,
            "password_hash": hashlib.sha256(password.encode()).hexdigest(),
            "email": email,
            "register_time": datetime.now().isoformat()
        })

        # 保存并备份
        try:
            with open(self.db_file, "w", encoding="utf-8") as f:
                json.dump(self.users, f, indent=2)
            self._backup_db()
            print("注册成功！")
            return True
        except IOError as e:
            print(f"保存失败: {e}")
            return False


# 使用示例
system = UserSystem()
system.register("charlie", "secure123", "charlie@example.com")



















